package com.taobao.client;

import java.util.HashMap;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.taobao.client.buyer.StatusMap;
import com.taobao.client.buyer.custom.CustomButton;
import com.taobao.client.component.pages.Pages;
import com.taobao.client.component.templete.HTMLTemplatePanel;
import com.taobao.client.obj.TopOrder;
import com.taobao.client.obj.TopRefund;
import com.taobao.client.obj.TopTrade;
import com.taobao.client.pages.CloseOrder;
import com.taobao.client.pages.DelayDate;
import com.taobao.client.pages.PriceChange;
import com.taobao.client.pages.RefundAgree;
import com.taobao.client.pages.RefundGetGood;
import com.taobao.client.pages.RefundNoGetGood;
import com.taobao.client.pages.RefundReject;
import com.taobao.client.util.PopBox;
import com.taobao.client.util.TradeTable;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 * 
 * @author jiangyongyuan@use.com.cn
 */
public class SellerPage extends HTMLTemplatePanel {

	static SellerPage instance;
	public static String HISOTYR = "SellerPage";

	public static SellerPage getInstance(Data d) {
		if (instance == null) {
			instance = new SellerPage(d);
		}
		return instance;
	}

	public static void doHistory(String token, Data d,
			VerticalPanel contentPanel) {
		if ("SellerPage".equals(token)) {
			contentPanel.add(getInstance(d));
		}
	}

	Data d;

	public SellerPage(Data d) {
		super("seller.html", "gwttemplate");
		this.d = d;
	}

	DateTimeFormat f = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss");

	protected void beforeFlushChildren() {
		instance = this;

		setWidth("800px");
		putWidget("content", content);

		// query refunds as a seller
		queryRefund();

		queryTrade();
	}

	/**
	 * Query the received refunds
	 */
	private void queryRefund() {
		RPC.getService().getSellerRefund(d.getSeller(),
				new AsyncCallback<List<TopRefund>>() {

					@Override
					public void onFailure(Throwable caught) {
						PopBox.error("获得退款失败", caught.getLocalizedMessage());

					}

					@Override
					public void onSuccess(List<TopRefund> result) {
						// Have refunds
						if (result != null) {
							if (result.size() > 0) {
								refundList = result;

								for (TopRefund r : result) {
									// if(r.getOid() == null)
									tradeRefundMap.put(r.getTid() + "", r);
									refundMap.put(r.getOid() + "", r);
									// else
									// refundMap.put(r.getOid() + "", r);
								}
								// drawTable();
							}
						}

					}
				});
	}

	private void queryTrade() {
		RPC.getService().tradeSoldGet(d.getSeller(),
				new AsyncCallback<List<TopTrade>>() {
					@Override
					public void onFailure(Throwable arg0) {
						PopBox.error("获得订单失败", arg0.getMessage());
					}

					@Override
					public void onSuccess(List<TopTrade> arg0) {
						if (arg0 != null && arg0.size() > 0) {
							rs = arg0;
							drawTable();
						} else {
							PopBox.error("获得订单出错", "您暂无订单");
						}
					}
				});
	}

	ClickHandler c = new ClickHandler() {
		@Override
		public void onClick(ClickEvent arg0) {
			Button source = (Button) arg0.getSource();
			String action = source.getText();

			String index = source.getTitle();

			String tid = "";

			TopOrder order = null;// 子订单根据设置在order处
			if (source instanceof CustomButton) {
				order = ((CustomButton) source).getOrder();
			}

			if (order != null) {
				tid = order.getTid();
			} else {
				TopTrade topTrade = rs.get(Integer.parseInt(index));
				tid = topTrade.getTid();
			}
			// if press change price
			if (action.equals(String_price)) {

				PriceChange.initOrder(tid);
				History.newItem(PriceChange.HISTORY);

			} else if (String_close.equals(action)) {
				CloseOrder co = CloseOrder.getCloseOrder();
				co.setTradeId(tid);
				History.newItem(CloseOrder.HISTORY_ITEM);

			} else if (String_delay.equals(action)) {
				DelayDate dd = DelayDate.getDelayDate();
				dd.setTradeId(tid);

				History.newItem(DelayDate.HISTORY_ITEM);
			} else if (String_refund_argee.equals(action)) {

				TopRefund refund = getRefund(tid);

				RefundAgree refundAgree = RefundAgree.getRefundAgree();
				refundAgree.setIds(tid, refund.getRefundId());
				History.newItem(RefundAgree.HISTORY_ITEM);

			} else if (String_refund_reject.equals(action)) {

				TopRefund refund = getRefund(tid);

				RefundReject rr = RefundReject.getRefundReject();
				rr.setIds(tid, refund.getRefundId());

				History.newItem(RefundReject.HISTORY_ITEM);

			} else if (String_refund_getGood.equals(action)) {

				TopRefund refund = getRefund(tid);

				RefundGetGood refundAgree = RefundGetGood.getRefundGetGood();
				refundAgree.setIds(tid, refund.getRefundId());
				History.newItem(RefundGetGood.HISTORY_ITEM);

			} else if (String_refund_nogetGood.equals(action)) {

				TopRefund refund = getRefund(tid);

				RefundNoGetGood rr = RefundNoGetGood.getRefundNoGetGood();
				rr.setIds(tid, refund.getRefundId());

				History.newItem(RefundNoGetGood.HISTORY_ITEM);

			} else if (String_send.equals(action)) {
				doSend(tid);
			}
		}
	};

	private void doSend(String tid) {
		RPC.getService().deliverySend(tid, new AsyncCallback<String>() {
			@Override
			public void onFailure(Throwable arg0) {
				PopBox.error("发货失败", arg0.getMessage());
			}

			@Override
			public void onSuccess(String arg0) {
				queryTrade();
			}
		});
	}

	public void drawTable() {
		soldTradePanel.clear();
		table = TradeTable.getTable();

		page = new Pages(rs.size()) {
			public void go(int current) {
				refresh(current);
			}
		};

		table.setWidget(0, 0, page);
		table.getFlexCellFormatter().setColSpan(0, 0, 2);

		soldTradePanel.add(table);

		content.clear();
		content.add(soldTradePanel);
		// d.home.addContent(content);
	}

	private void refresh(int page) {
		int start = (page - 1) * Pages.VISIBLE_ITEM_COUNT;

		while (table.getRowCount() > 3) {
			table.removeRow(table.getRowCount() - 1);
		}

		for (int i = 0; i < Pages.VISIBLE_ITEM_COUNT; i++) {

			if (rs.size() <= start)
				break;

			final TopTrade tt = rs.get(start);
			System.out.println("Trade = " + tt.getTid());
			if (tt == null)
				break;

			// Get the corresponding refund object
			// TopRefund tr = getRefund(tt.getTid());

			String title = "";
			if (tt.getTopOrders() != null) {
				TopOrder topOrder = tt.getTopOrders().get(0);
				title = topOrder.getTitle();
			}

			String output = "<p>" + "<img border=0 src='" + tt.getPicPath()
					+ "' width='25' height='25' >" + "	商品名：" + title + "</p>";
			output += "<p>	价格：" + tt.getPrice() + "	订单号：" + tt.getTid() + "   "
					+ "</p>";
			output += "<p>买家:" + tt.getBuyerNick() + " ";
			String consignTime = "";

			output += "确认收货时间:" + consignTime + " </p>";

			output += "<p>状态:" + StatusMap.get(tt.getStatus()) + " ";

			output += "创建时间:" + f.format(tt.getCreated()) + "</p><br>";

			HTML tempH = new HTML(output);
			tempH.setTitle(tt.getSellerNick());

			Grid grid = new Grid(10, 2);

			grid.removeStyleName("cw-FlexTable");

			Button x修改价格 = new Button(String_price);
			Button y延长收货 = new Button(String_delay);
			Button t同意退款 = new Button(String_refund_argee);
			Button j拒绝退款 = new Button(String_refund_reject);
			Button g关闭订单 = new Button(String_close);
			Button f发货 = new Button(String_send);

			CustomButton t退货成功 = new CustomButton(String_refund_getGood);
			CustomButton t退货失败 = new CustomButton(String_refund_nogetGood);

			x修改价格.addClickHandler(c);
			y延长收货.addClickHandler(c);
			t同意退款.addClickHandler(c);
			g关闭订单.addClickHandler(c);
			j拒绝退款.addClickHandler(c);
			f发货.addClickHandler(c);

			t退货成功.addClickHandler(c);
			t退货失败.addClickHandler(c);

			//
			TopRefund refund = getRefund(tt.getTid());

			List<TopOrder> l = tt.getTopOrders();
			int size = 0 ;
			if( l != null)
				size = l.size();
			
			if (refund == null || size > 2) {//有子订单则不显示退款相关资料
				t同意退款.setVisible(false);
				j拒绝退款.setVisible(false);
				t退货成功.setVisible(false);
				t退货失败.setVisible(false);
			}
			/**
			 * TRADE_NO_CREATE_PAY(没有创建支付宝交易) WAIT_BUYER_PAY(等待买家付款)
			 * WAIT_SELLER_SEND_GOODS(等待卖家发货,即:买家已付款)
			 * WAIT_BUYER_CONFIRM_GOODS(等待买家确认收货,即:卖家已发货) TRADE_FINISHED(交易成功)
			 * TRADE_CLOSED(交易关闭) TRADE_CLOSED_BY_TAOBAO(交易被淘宝关闭)
			 * ALL_WAIT_PAY(包含：WAIT_BUYER_PAY、TRADE_NO_CREATE_PAY)
			 * ALL_CLOSED(包含：TRADE_CLOSED、TRADE_CLOSED_BY_TAOBAO)
			 */
			if ("WAIT_BUYER_PAY TRADE_NO_CREATE_PAY ".indexOf(tt.getStatus()) >= 0) {
				f发货.setVisible(false);
				y延长收货.setVisible(false);
				x修改价格.setVisible(true);
			} else
				x修改价格.setVisible(false);

			if (tt.getStatus().equalsIgnoreCase("WAIT_BUYER_CONFIRM_GOODS"))
				y延长收货.setVisible(true);
			else
				y延长收货.setVisible(false);

			if ("WAIT_SELLER_SEND_GOODS".indexOf(tt.getStatus()) >= 0)
				f发货.setVisible(true);
			else
				f发货.setVisible(false);

			if ("TRADE_CLOSED_BY_TAOBAO".indexOf(tt.getStatus()) >= 0)
				g关闭订单.setVisible(false);

			f发货.setTitle(start + "");
			y延长收货.setTitle(start + "");
			t同意退款.setTitle(start + "");
			g关闭订单.setTitle(start + "");
			x修改价格.setTitle(start + "");
			t退货成功.setTitle(start + "");
			t退货失败.setTitle(start + "");
			j拒绝退款.setTitle(start++ + "");

			grid.setWidget(0, 0, x修改价格);
			grid.setWidget(0, 1, y延长收货);
			grid.setWidget(1, 0, t同意退款);
			grid.setWidget(1, 1, g关闭订单);
			grid.setWidget(2, 0, j拒绝退款);
			grid.setWidget(2, 1, f发货);
			grid.setWidget(3, 0, t退货成功);
			grid.setWidget(4, 0, t退货失败);

			if (tt.getTopOrders() != null && tt.getTopOrders().size() > 1) {
				Button l查看子订单 = new Button("查看子订单");
				l查看子订单.addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent arg0) {
						showOrder(tt);
					}
				});
				grid.setWidget(3, 0, l查看子订单);
			}
			table.setWidget(i + 2, 0, tempH);
			table.setWidget(i + 2, 1, grid);
		}
	}

	private void showOrder(TopTrade trade) {

		// 创建弹出窗口
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("子订单查看");
		dialogBox.setAnimationEnabled(true);

		Button closeButton = new Button("关闭");
		// We can set the id of a widget by accessing its
		// Element
		closeButton.getElement().setId("closeButton");

		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogBox.setWidget(dialogVPanel);
		// 弹出窗口完毕

		int i = 0;
		List<TopOrder> topOrders = trade.getTopOrders();

		FlexTable table = new FlexTable();
		for (TopOrder tt : topOrders) {

			String output = "<p>" + "<img border=0 src='" + tt.getPicPath()
					+ "' width='25' height='25' >" + "	商品名：" + tt.getTitle()
					+ "</p>";
			output += "<p>	价格：" + tt.getPrice() + "	订单号：" + tt.getTid() + "   "
					+ "</p>";
			output += "<p>买家:" + tt.getBuyerNick() + " ";
			String consignTime = "";

			output += "确认收货时间:" + consignTime + " </p>";

			output += "<p>状态:" + StatusMap.get(tt.getStatus()) + " ";

			// output += "创建时间:" + f.format(tt.getCreated()) + "</p><br>";

			HTML tempH = new HTML(output);
			tempH.setTitle(tt.getSellerNick());

			Grid grid = new Grid(10, 2);

			grid.removeStyleName("cw-FlexTable");

			CustomButton x修改价格 = new CustomButton(String_price);
			// Button y延长收货 = new Button(String_delay);
			CustomButton t同意退款 = new CustomButton(String_refund_argee);
			CustomButton j拒绝退款 = new CustomButton(String_refund_reject);

			CustomButton t退货成功 = new CustomButton(String_refund_getGood);
			CustomButton t退货失败 = new CustomButton(String_refund_nogetGood);

			// Button g关闭订单 = new Button(String_close);
			// Button f发货 = new Button(String_send);
			// y延长收货.addClickHandler(c);
			// g关闭订单.addClickHandler(c);
			// f发货.addClickHandler(c);

			x修改价格.addClickHandler(c);
			t同意退款.addClickHandler(c);
			j拒绝退款.addClickHandler(c);

			t退货成功.addClickHandler(c);
			t退货失败.addClickHandler(c);

			//
			TopRefund refund = getRefund(tt.getTid());

			if (refund == null) {
				t同意退款.setVisible(false);
				j拒绝退款.setVisible(false);
				t退货成功.setVisible(false);
				t退货失败.setVisible(false);
			}
			/**
			 * TRADE_NO_CREATE_PAY(没有创建支付宝交易) WAIT_BUYER_PAY(等待买家付款)
			 * WAIT_SELLER_SEND_GOODS(等待卖家发货,即:买家已付款)
			 * WAIT_BUYER_CONFIRM_GOODS(等待买家确认收货,即:卖家已发货) TRADE_FINISHED(交易成功)
			 * TRADE_CLOSED(交易关闭) TRADE_CLOSED_BY_TAOBAO(交易被淘宝关闭)
			 * ALL_WAIT_PAY(包含：WAIT_BUYER_PAY、TRADE_NO_CREATE_PAY)
			 * ALL_CLOSED(包含：TRADE_CLOSED、TRADE_CLOSED_BY_TAOBAO)
			 */
			if ("WAIT_BUYER_PAY TRADE_NO_CREATE_PAY ".indexOf(tt.getStatus()) >= 0) {
				// f发货.setVisible(false);
				// y延长收货.setVisible(false);
				x修改价格.setVisible(true);
			} else
				x修改价格.setVisible(false);

			// if (tt.getStatus().equalsIgnoreCase("WAIT_BUYER_CONFIRM_GOODS"))
			// y延长收货.setVisible(true);
			// else
			// y延长收货.setVisible(false);

			// if ("WAIT_SELLER_SEND_GOODS".indexOf(tt.getStatus()) >= 0)
			// f发货.setVisible(true);
			// else
			// f发货.setVisible(false);

			// f发货.setTitle(start + "");
			// y延长收货.setTitle(start + "");
			t同意退款.setOrder(tt);// .setTitle(start + "");
			// g关闭订单.setTitle(start + "");
			x修改价格.setOrder(tt);// .setTitle(start + "");
			j拒绝退款.setOrder(tt);// .setTitle(start++ + "");

			t退货成功.setOrder(tt);
			t退货失败.setOrder(tt);

			grid.setWidget(0, 0, x修改价格);
			// grid.setWidget(0, 1, y延长收货);
			grid.setWidget(1, 0, t同意退款);
			// grid.setWidget(1, 1, g关闭订单);
			grid.setWidget(2, 0, j拒绝退款);
			// grid.setWidget(2, 1, f发货);

			grid.setWidget(3, 0, t退货成功);
			grid.setWidget(4, 0, t退货失败);

			table.setWidget(i + 2, 0, tempH);
			table.setWidget(i + 2, 1, grid);
			i++;
		}

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});

		dialogVPanel.add(table);
		dialogVPanel.add(closeButton);
		dialogBox.show();
		dialogBox.center();
	}

	/**
	 * 
	 * @param tradeId
	 *            the trade id
	 * @return if the trade is refunded, return the refund object, or return
	 *         null
	 */
	private TopRefund getRefund(String tradeId) {
		// Have a list of refunds
		TopRefund topRefund = refundMap.get(tradeId);

		if (topRefund == null)
			tradeRefundMap.get(tradeId);

		return topRefund;
	}

	private VerticalPanel soldTradePanel = new VerticalPanel();
	private VerticalPanel content = new VerticalPanel();
	List<TopTrade> rs;
	List<TopRefund> refundList;

	HashMap<String, TopRefund> refundMap = new HashMap<String, TopRefund>();
	HashMap<String, TopRefund> tradeRefundMap = new HashMap<String, TopRefund>();

	FlexTable table;

	final String String_price = "修改价格";
	final String String_delay = "延长收货";
	final String String_refund_argee = "同意退款";
	final String String_refund_getGood = "退货后同意退款";
	final String String_refund_nogetGood = "退货后拒绝退款";
	final String String_refund_reject = "拒绝退款";
	final String String_close = "关闭订单";
	final String String_send = "发货";
	Pages page;
}
